﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Timer = System.Timers.Timer;

namespace DataCollect
{
    public partial class Service1 : ServiceBase
    {
        private readonly Timer CollectTimer;
        SerialPort serialPort;
        string portName = "COM5";
        byte[] bytes, buffer;
        internal void CollectTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            DateTime today = DateTime.Today;
            //if (today.Hour == 6 || today.Hour == 22)
            //{
            //    return;
            //}
            try
            {
                serialPort = new SerialPort();
                // 设置串口参数
                serialPort.PortName = portName; // 串口端口号，根据实际情况设置
                serialPort.BaudRate = 9600; // 波特率，根据实际情况设置
                serialPort.Parity = Parity.Even; // 校验位 偶校验
                serialPort.DataBits = 8; // 数据位
                serialPort.StopBits = StopBits.One; // 停止位

                bool isInUse = IsComPortInUse(portName);

                if (isInUse)
                {
                    LogUtils.Info($"{portName} is in use.");
                }
                else
                {
                    LogUtils.Info($"{portName} is available.");
                    serialPort.Open();
                    bytes = HexStringToByteArray("FCFCFC080109");
                    serialPort.Write(bytes, 0, bytes.Length);
                    Thread.Sleep(500);
                    buffer = new byte[serialPort.BytesToRead];
                    serialPort.Read(buffer, 0, buffer.Length);
                    string returnData = BitConverter.ToString(buffer).Replace("-", "");
                    if (returnData.Replace(" ", "").Length > 6)
                    {
                        returnData = returnData.Replace(" ", "").Substring(6);
                    }
                    else
                    {
                        return;
                    }
                    string result = returnData.Substring(12, 8);
                    decimal vol = ConvertHexToDecimal(result, 3, 1);
                    if (vol > 0)
                    {
                        LogUtils.Info($"{vol} is collected.");
                        GasCollectionData data = new GasCollectionData
                        {
                            Uuid = Guid.NewGuid().ToString(),
                            Version = 1,
                            Amount = vol,
                            CreateDate = DateTime.Now,
                            Source = "燃油加注2"
                        };
                        SqlSugarHelper.Db.Insertable(data).ExecuteCommand();
                        LogUtils.Info($"{vol} is saved.");
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtils.Info(ex.Message);
            }
            finally
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }
                serialPort.Dispose();
            }
        }

        byte[] HexStringToByteArray(string hex)
        {
            int NumberChars = hex.Length;
            byte[] bytes = new byte[NumberChars / 2];
            for (int i = 0; i < NumberChars; i += 2)
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            return bytes;
        }

        decimal ConvertHexToDecimal(string hexValue, int intLength, int decimalLength)
        {
            intLength *= 2;
            decimalLength *= 2;
            string format = "";
            for (int i = 0; i < intLength; i++)
            {
                format += "0";
            }
            format += ".";
            for (int i = 0; i < decimalLength; i++)
            {
                format += "0";
            }
            string intPart = hexValue.Substring(0, intLength);
            string decimalPart = hexValue.Substring(intLength, decimalLength);

            return decimal.Parse(intPart + "." + decimalPart);
        }

        public bool IsComPortInUse(string portName)
        {
            bool inUse = true;

            SerialPort serialPort = new SerialPort(portName);

            try
            {
                serialPort.Open();
                inUse = false;
            }
            catch
            {
                // 端口被占用时会抛出异常
            }
            finally
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }
                serialPort.Dispose();
            }

            return inUse;
        }

        public Service1()
        {
            InitializeComponent();

            CollectTimer = new Timer(3600000); //1.5s
            CollectTimer.Elapsed += CollectTimer_Elapsed;
        }

        protected override void OnStart(string[] args)
        {
            CollectTimer.Start();
        }

        protected override void OnStop()
        {
            CollectTimer.Stop();
        }
    }
}
